#include "config.h"
#include <stdio.h>
#include <stdlib.h>

void free_app_config(AppConfig *config);

AppConfig *parse_config(const char *filename) {
	FILE *fp = fopen(filename, "r");
	if (!fp) return NULL;

	fseek(fp, 0, SEEK_END);
	long len = ftell(fp);
	fseek(fp, 0, SEEK_SET);
	char *data = malloc(len + 1);
	fread(data, 1, len, fp);
	fclose(fp);
	data[len] = '\0';

	cJSON *root = cJSON_Parse(data);
	free(data);
	if (!root) return NULL;

	AppConfig *config = calloc(1, sizeof(AppConfig));

	// 解析基础字段
	config->name = strdup(cJSON_GetStringValue(cJSON_GetObjectItem(root, "name")));
	config->port = cJSON_GetObjectItem(root, "port")->valueint;

	// 解析redis配置
	cJSON *redis = cJSON_GetObjectItem(root, "redis");
	if (redis) {
		config->redis.host = strdup(cJSON_GetStringValue(cJSON_GetObjectItem(redis, "host")));
		config->redis.port = cJSON_GetObjectItem(redis, "port")->valueint;
	}

	// 解析服务数组
	cJSON *services = cJSON_GetObjectItem(root, "services");
	if (services && cJSON_IsArray(services)) {
		config->services.count = cJSON_GetArraySize(services);
		config->services.items = calloc(config->services.count, sizeof(Service));

		for (size_t i = 0; i < config->services.count; i++) {
			cJSON   *item = cJSON_GetArrayItem(services, i);
			Service *s    = &config->services.items[i];

			s->id      = cJSON_GetObjectItem(item, "id")->valueint;
			s->service = strdup(cJSON_GetStringValue(cJSON_GetObjectItem(item, "service")));
			s->enabled = cJSON_IsTrue(cJSON_GetObjectItem(item, "enabled"));
		}
	}

	cJSON_Delete(root);
	return config;
}

void print_config(const AppConfig *config) {
	printf("Application Config:\n");
	printf("Name: %s\n", config->name);
	printf("Port: %d\n", config->port);

	printf("\nRedis Config:\n");
	printf("  Host: %s\n", config->redis.host);
	printf("  Port: %d\n", config->redis.port);

	printf("\nServices (%zu):\n", config->services.count);
	for (size_t i = 0; i < config->services.count; i++) {
		const Service *s = &config->services.items[i];
		printf("[%zu] ID: %d, Service: %s, Enabled: %s\n", i, s->id, s->service, s->enabled ? "true" : "false");
	}
}

void free_app_config(AppConfig *config) {
	if (!config) return;

	free(config->name);
	free(config->redis.host);

	for (size_t i = 0; i < config->services.count; i++) {
		free(config->services.items[i].service);
	}
	free(config->services.items);

	free(config);
}

int main() {
	printf("=== config c demo ===\n");
	AppConfig *config = parse_config("etc/config.json");
	if (!config) {
		fprintf(stderr, "Failed to load config\n");
		return 1;
	}

	print_config(config);
	free_app_config(config);
	return 0;
}
